package Socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

public class TcpClient {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        //创建socket
        try {
            Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9999);

            //接收数据，使用子线程
            new MyThreadTcpC(socket);

            //获取输出流
            OutputStream outputStream = socket.getOutputStream();
            //发送数据
            while (true){
                System.out.print("请输入要发送的信息:");
                String str = scanner.nextLine();
                outputStream.write(str.getBytes());
                if("bye".equals(str)){
                    System.out.println("再见");
                    break;
                }

            }






        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}


class MyThreadTcpC extends Thread{

    Socket socket;
    public MyThreadTcpC(Socket socket){
        this.socket = socket;
    }




    @Override
    public void run() {
        //接收数据
        try {

                InputStream in = socket.getInputStream();
                byte[] bys = new byte[1024];
                in.read(bys);
                String str = new String(bys,"utf-8");
                System.out.println("服务器发来的数据"+str);





        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
